package logic

import (
	"baidutieba/models/mysql"
	"baidutieba/tiebarpc/internal/svc"
	"baidutieba/tiebarpc/tiebarpc"
	"context"

	"github.com/zeromicro/go-zero/core/logx"
)

type TieBaListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewTieBaListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TieBaListLogic {
	return &TieBaListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *TieBaListLogic) TieBaList(in *tiebarpc.TieBaListRequest) (*tiebarpc.TieBaListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	var tieba []mysql.TieBa
	mysql.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).Order("num desc").Find(&tieba)
	var tiebaList []*tiebarpc.TieBaList
	for _, ba := range tieba {
		list := tiebarpc.TieBaList{
			Title:   ba.Title,
			Image:   ba.Image,
			Num:     ba.Num,
			UserId:  ba.UserId,
			Context: ba.Context,
			Class:   ba.Class,
		}
		tiebaList = append(tiebaList, &list)
	}
	return &tiebarpc.TieBaListResponse{
		List: tiebaList,
	}, nil
}
